<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Victor
 * Date: 13.11.11
 * Time: 15:26
 * To change this template use File | Settings | File Templates.
 */

class Core_FrontController
{
    private static $instance = null;
    private static $routes = array();

    private function Core_FrontController()
    {
    }

    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new Core_FrontController();
        }
        return self::$instance;
    }

    public function setRoutes($routes)
    {
        self::$routes = $routes;
    }

    public function run()
    {
        $uri = $this->getURI();
        $this->call($uri);
    }

    private function getURI()
    {
        $segments = null;
        $access = false;
        if (!empty($_GET)) {

            // fdsf/fdsf/fsdfsd/fsdfsd/fsdf
            $uri = trim($_GET['param'], '/');

            foreach (self::$routes as $routePattern => $routeInternal) {
                if (!preg_match($routePattern, $uri)) continue;
                $access = preg_replace($routePattern, $routeInternal, $uri);
            }
        }
        if (!$access) {

            $access = 'index/index';

        }

        $segments = explode('/', $access);
        return $segments;
    }

    private function call($segments)
    {
        //www.ds.xom/Car/info/22/1990/04
        //Car info 25
        $parameters = null;
        $controller = $segments[0];  //Car
        $action = $segments[1];   //info
        if (count($segments) > 2)
            $parameters = array_splice($segments, 2);
        if (isset($parameters) && count($parameters) != 0) {
           $className = $controller . 'Controller';
            //CarController
            $function = $action . 'Action';
            //infoAction

            $obj = new $className();

            $obj->setRegistry($this->registry);



            call_user_func_array(array($obj, $function), $parameters);

        } else {

            $className = $controller . 'Controller';
            $function = $action . 'Action';
            $obj = new $className();

            $obj->setRegistry($this->registry);


            $obj->$function();
        }
    }

}
